package fr.miage.dao;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import org.apache.log4j.Logger;

import com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException;

import fr.miage.connexion.ConnexionBD;
import fr.miage.model.Address;

public class AddressDAO {
	
	private Logger logger = Logger.getRootLogger();

	public Address getById(String idAddress) {
		ResultSet res = null;
		String query = "select * from adress WHERE idAdress="+idAddress;
		Statement st = null;
		Address address = null;
		try {
			st = ConnexionBD.getInstance().getConn().createStatement();
			res = st.executeQuery(query);
			if(res.next()){
				address = getAddress(res);
			}else{
				return null;
			}
		} catch (SQLException ex) {
			logger.error(ex);
		} finally {
			try {
				if (res != null) {
					res.close();
				}
				if (st != null) {
					st.close();
				}
			} catch (SQLException e) {
				logger.error(e);
			}
		}
		
		return address;
	}

	private Address getAddress(ResultSet res) {
		Address address = new Address();
		try {
			address.setIdAddress(res.getLong("idAdress"));
			address.setPlace(res.getString("place"));
			address.setLocation(res.getString("location"));
			address.setLatitude(res.getLong("latitude"));
			address.setLongitude(res.getLong("longitude"));
		} catch (SQLException e) {
			logger.error(e);
		}
		return address;
	}

	public Address getAddressByUser(String idUser) {
		ResultSet res = null;
		String query = "select * from adress a inner join user u on a.idAdress = u.idAdress WHERE u.idUser="+idUser;
		Statement st = null;
		Address address = null;
		try {
			st = ConnexionBD.getInstance().getConn().createStatement();
			res = st.executeQuery(query);
			if(res.next()){
				address = getAddress(res);
			}else{
				return null;
			}
		} catch (SQLException ex) {
			logger.error(ex);
		} finally {
			try {
				if (res != null) {
					res.close();
				}
				if (st != null) {
					st.close();
				}
			} catch (SQLException e) {
				logger.error(e);
			}
		}
		
		return address;
	}

	public int addAddress(Address address) {
		int res = 0;
		String query = "insert into adress(place, location, latitude, longitude) values ('"+address.getPlace()+"', '"+address.getLocation()+"', "+address.getLatitude()+", "+address.getLongitude()+")";
		Statement st = null;
		try {
			st = ConnexionBD.getInstance().getConn().createStatement();
			res = st.executeUpdate(query);
			return res;
		} catch(MySQLIntegrityConstraintViolationException e){
			logger.error(e);
			e.printStackTrace();
			return -1;
		} catch (SQLException ex) {
			logger.error(ex);
			ex.printStackTrace();
			return res;
		} finally {
			try {
				if (st != null) {
					st.close();
				}
			} catch (SQLException e) {
				logger.error(e);
				e.printStackTrace();
			}
		}
	}

}
